<?php session_start();

include_once 'questions.php';
include_once 'db_utility.php';
include_once 'visibility.php';
include_once 'opr_confirm.php';

if(validate_captcha()) {
    
    // 1. confirm all temporary operations user has done
    if(!confirm_all_operations ($_SESSION['user']['u_visibility'], 
       $_SESSION['stories']['onURL'], 
       $_SESSION['stories']['onButton']))
    {
        echo "An error has occured when confirming operations [user_complete.php]\n";
        exit;
    }

    $conn = db_connect();
    
    // 2. collect user answers and store them in db
    $old_user = $_SESSION['user']['u_id'];
    $tb = "experiments_q_and_a";

    foreach   ($_POST   as   $key   =>   $value) {
        if(strval($key) != 'captcha') {
            $question = $question_array[$key];
            $answer = $value;
            $strsql="INSERT INTO $tb (experiment_id, question, answer)
							    		 VALUES('$old_user','$question', '$answer')";
            $result = $conn->query($strsql);
            if(!$result){
                echo "An error has occured when inserting a Q&A record to the table\n";
                echo "Error:".$conn->errno. "  ".$conn->error;
                $conn->close();
                exit;
            }
        }
    }


    // 3. insert finish event to experiment table
    $now = time();
    $now = date('YmdHis',$now);
    $strsql="UPDATE experiments SET end_time= $now, status='submitted' WHERE experiment_id='$old_user'";
    $result = $conn->query($strsql);
    if(!$result){
        echo "An error has occured when adding an end_timestamp to experiment table[opr_complete.php]\n";
        echo "Error:".$conn->errno. "  ".$conn->error;
        $conn-close();
        exit;
    }

    $conn -> close();
    
    
    // 4. destroy user session
    $result_dest = session_destroy();

    if (!empty($old_user)) {
        if ($result_dest) {
            // if they were logged in and are now logged out
            echo "yes";
        } 
        else {
            // they were logged in and could not be logged out
            echo "session can not be destroyed";
        }
    }
    else {
        // if they weren't logged in but came to this page somehow
        echo "user has not been created";
    }
}
else {
    echo "captcha is incorrect";
}
?>